package com.efast.cafe.commponent.es.socketio.listener;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.DisconnectListener;
import com.efast.cafe.commponent.es.socketio.properties.SocketIOConfig;
import com.efast.cafe.commponent.es.socketio.util.SocketIOUtil;
import com.efast.cafe.framework.constant.FrameConstant;
import com.efast.cafe.framework.spring.SpringContextUtils;

/**
 * 客户端断开链接后
 * @author fxm
 *
 */
public class SocketIODisconnectListener implements DisconnectListener{
	private final static Logger log = LoggerFactory.getLogger(SocketIODisconnectListener.class);
	private StringRedisTemplate redisTemplate;	
	private SocketIOConfig config;
	public SocketIODisconnectListener(SocketIOConfig config){
		this.config = config;
	}
	
	@Override
	public void onDisconnect(SocketIOClient client) {
		String uid = client.get(FrameConstant.SOCKET_UID);
		SocketIOUtil.removeClient(uid);
		redisTemplate = SpringContextUtils.getBean(StringRedisTemplate.class);
		//redisTemplate.delete(client.getSessionId().toString());
		log.info("client:"+client.getSessionId().toString()+",断开socket.io server,IP："+client.getHandshakeData().getAddress().toString());
		
		RedisMessageListenerContainer container = SocketIOUtil.getMessageListener(uid);
		if(container!=null)
			container.stop();
		SocketIOUtil.removeContainer(uid);
		SocketIOUtil.additionDisconnectCounter(uid);
		SocketIOUtil.additionAllDisconnectCounter();
		redisTemplate.opsForHash().delete(FrameConstant.SOCKET_IO_ONLINE_TOKEN+":"+config.getInstance(), uid);
	}

}
